package com.ad.pet.app.account.info;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.AccountContract;
import com.ad.pet.app.account.AccountPresenter;
import com.ad.pet.app.photo.model.ImageItem;
import com.ad.pet.common.data.utils.FileUtil;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.BottomSheetUtil;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.PermissionManager;
import com.ad.pet.common.structure.PhotoManager;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.key.TokenKey;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.presenter.photo.PhotoContract;
import com.ad.pet.common.structure.presenter.photo.PhotoPresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.account.Account;
import com.ad.pet.models.remote.account.AccountPet;
import com.ad.pet.models.remote.account.pet.PetCateFirst;
import com.ad.pet.models.remote.account.pet.PetColor;
import com.just.agentweb.AgentWebConfig;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.ShareBoardConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * e7188b637f3877fe843104d9c54653ff4b9b006c
 * Created by SEELE on 2018/8/7.
 */

public class PersonBaseInfoActivity extends AppToolbarActivity implements AccountContract.View, PhotoContract.View {
    private boolean mIsDel;
    @Inject
    RxDisposable mRxDisposable;
    @Inject
    FileUtil mFileUtil;
    private File mFile;
    @Inject
    PermissionManager mPermissionManager;

    private BottomSheetDialog mPhotoDialog;
    private View mDialogView;
    private Button mButCancel;
    private Button mButOpen;
    private Button mButPhoto;

    @Inject
    PhotoPresenter mPhotoPresenter;

    @BindView(R.id.iv_head)
    ImageView mIvHead;
    @BindView(R.id.tv_vip_name)
    EditText mTvVipName;
    @BindView(R.id.relativeLayout_address)
    RelativeLayout mRelativeLayoutAddress;

    @BindView(R.id.btn_out_login)
    Button mBtnOutLogin;
    @BindView(R.id.relativeLayout_language)
    RelativeLayout mRelativeLayoutLanguage;
    @BindView(R.id.relativeLayout_age)
    RelativeLayout mRelativeLayoutVersion;
    @BindView(R.id.relativeLayout_share)
    RelativeLayout mRelativeLayoutShare;

    @BindView(R.id.tv_version)
    EditText mTvVersion;

    @BindView(R.id.tv_birth)
    TextView tvBirth;
    @Inject
    AccountPresenter mAccountPresenter;
    @BindView(R.id.iv_as)
    ImageView ivER;
    @BindView(R.id.tv_nick_name)
    EditText tvNickName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_version_bottom)
    TextView tvVersionBottom;
    private Drawable drawableMale;
    private Drawable drawableFamale;
    private Account account;


    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();
        mToolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        mToolbar.setLeftIcon(R.drawable.whitefanhui);
        mToolbar.setNextText("保存");
        mToolbar.setNextOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(account.getUser_headimg())){
                    ToastUtil.getToastUtil().showShort("请选择头像");
                    return;
                }
                if (TextUtils.isEmpty(mTvVipName.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入用户名");
                    return;
                }
                if (TextUtils.isEmpty(tvNickName.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入昵称");
                    return;
                }
                if (TextUtils.isEmpty(account.getBirthday())){
                    ToastUtil.getToastUtil().showShort("请选择生日");
                    return;
                }
                if (TextUtils.isEmpty(mTvVersion.getText().toString())){
                    ToastUtil.getToastUtil().showShort("请输入手机号");
                    return;
                }
                mAccountPresenter.upPersonInfo(account.getUser_headimg(),mTvVipName.getText().toString(),tvNickName.getText().toString(),account.getSex()+"",account.getBirthday(),mTvVersion.getText().toString());
            }
        });

    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_person_base_info;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mAccountPresenter.onCreate(this);
        mPhotoPresenter.onCreate(this);
        account = (Account) getIntent().getSerializableExtra("account");

        if (!TextUtils.isEmpty(account.getUser_headimg())){
            GlideUtil.loadCircle(mActivity,account.getUser_headimg(),mIvHead);
        }
        mTvVipName.setText(TextUtils.isEmpty(account.getUser_name())?"":account.getUser_name());
        tvNickName.setText(TextUtils.isEmpty(account.getNick_name())?"":account.getNick_name());


        drawableMale = getResources().getDrawable(
                R.drawable.ic_male);
        drawableFamale = getResources().getDrawable(
                R.drawable.ic_fale);

        setSex(account.getSex());
        tvBirth.setText(TextUtils.isEmpty(account.getBirthday())?"":account.getBirthday());
        mTvVersion.setText(account.getUser_tel());

        mPermissionManager.setRxPermissions(new RxPermissions(this));
        mDialogView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_photo, null);
        mButCancel = mDialogView.findViewById(R.id.but_cancel);
        mButOpen = mDialogView.findViewById(R.id.but_open);
        mButPhoto = mDialogView.findViewById(R.id.but_photo);

        mPhotoDialog = new BottomSheetDialog(this);
        mPhotoDialog.setContentView(mDialogView);
        BottomSheetUtil.statusBarTranslucent(mPhotoDialog);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {
        mIvHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BottomSheetUtil.collapsedDialog(mDialogView);
                mPhotoDialog.show();
            }
        });

        mButPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        Navigation.goPhotoLoaderActivity(mActivity, PhotoManager.REQUEST_CODE_CHECK_IMAGE, 0);
                    }
                }, getString(R.string.storage), Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE));
            }
        });
        mButCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
            }
        });
        //打开相机
        mButOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
                //打开相机
                mRxDisposable.add(mPermissionManager.checkPermissionShowNick(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        mFile = new File(mFileUtil.getRootDir(), System.currentTimeMillis() + ".jpg");
                        //打开相机
                        PhotoManager.openCamera(mActivity, mFile, PhotoManager.REQUEST_CODE_OPEN_CAMERA);
                    }
                }, getString(R.string.camera), Manifest.permission.CAMERA));
            }
        });
        mBtnOutLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.createDialog(mActivity, getString(R.string.tips), getString(R.string.is_out_login), true, getString(R.string.cancel), null, getString(R.string.confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        mAccountPresenter.loginOut(SpUtil.getInstance().getString(TokenKey.TOKEN));
                        outLogin();

                    }
                }).show();
            }
        });
        mRelativeLayoutAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = 0;

                    i = account.getSex();


                DialogUtil.createSingleChoiceItemsDialog(mActivity, "选择性别", new String[]{"保密", "男", "女"}, i, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        setSex(i);
                        account.setSex(i);
                    }
                }).show();
            }
        });


        mRelativeLayoutShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareBoardConfig mBoardConfig = new ShareBoardConfig();
                mBoardConfig.setIndicatorVisibility(false);
                UMImage umImage = new UMImage(mActivity, R.drawable.ic_login_bg);
                umImage.setThumb(umImage);
                new ShareAction(mActivity)
                        .withMedia(umImage)
                        .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {

                            }

                            @Override
                            public void onResult(SHARE_MEDIA share_media) {

                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                ToastUtil.getToastUtil().showShort(throwable.getMessage());
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {

                            }
                        })
                        .open(mBoardConfig);
            }//13521938016
        });

        mRelativeLayoutVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(mActivity, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        String time = i + "/" + (i1 + 1) + "/" + i2;
                        tvBirth.setText(time);
//                        accountPet.setBirthday(TimeFormatUtil.dateToStamp(time));
                        account.setBirthday(time);
                    }
                }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
            }
        });
//        mRelativeLayoutLanguage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                DialogUtil.createSingleChoiceItemsDialog(mActivity, getString(R.string.langue_chose), getResources().getStringArray(R.array.language_select_items), TextUtils.equals("en", SpUtil.getInstance().getString(Constant.LANGUAGE)) ? 0 : 1, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        SpUtil.getInstance().putString(Constant.LANGUAGE, which == 0 ? "en" : "cn");
//
//                        Logger.e("SystemLanguage----->" + SpUtil.getInstance().getString(Constant.LANGUAGE));
//                        Navigation.freshView(mActivity);
////
//
//
//                    }
//                }).show();
//            }
//        });

        ivER.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Navigation.goStyleShopList(mActivity);
            }
        });

    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return mAccountPresenter;
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {
            ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void loginOutSuccess() {

        ToastUtil.getToastUtil().showShort(getString(R.string.out_success));
    }

    private void outLogin() {
        String uid = SpUtil.getInstance().getString(Constant.USER_ID, "");
//        PushServiceFactory.getCloudPushService().removeAlias(LyxUtils.getIMEI(mActivity) + (TextUtils.isEmpty(uid) ? "" : "-" + uid), new CommonCallback() {
//            @Override
//            public void onSuccess(String s) {
//                Logger.e("注销：" + s);
//            }
//
//            @Override
//            public void onFailed(String s, String s1) {
//                Logger.e(s + "---" + s1);
//            }
//        });

        SpUtil.getInstance().putString(TokenKey.TOKEN, "");
        SpUtil.getInstance().putString(Constant.PHPSESSID, "");
        SpUtil.getInstance().putString(Constant.USER_ID, "");
        SpUtil.getInstance().putString("head_url", "");
        SpUtil.getInstance().putString("nick_name", "");
        for (int i = 0; i < 10; i++) {
            SpUtil.getInstance().putBoolean("get" + i, false);
        }
//        AlibcLogin.getInstance().logout(mActivity, new LogoutCallback() {//退出淘宝登陆
//            @Override
//            public void onSuccess() {
//
//            }
//
//            @Override
//            public void onFailure(int i, String s) {
//
//            }
//        });
        RxBus.getDefault().post("set_message_number_success");
        AgentWebConfig.removeAllCookies();
        AgentWebConfig.clearDiskCache(mActivity);
//        App.getApp().initInjector();
//        Glide.get(mActivity).register(          //使用okhttp作为图片请求
//                GlideUrl.class
//                , InputStream.class
//                , new OkHttpUrlLoader.Factory(App.getApp().getApplicationComponent().getOkHttpClient()));
        ToastUtil.getToastUtil().showShort(getString(R.string.out_success));
        Intent intent = new Intent();
        intent.putExtra("goHome", 1);
        setResult(RESULT_OK, intent);
        finish();

    }

    @Override
    public void getUserInfoSuccess(Account account) {

    }

    @Override
    public void getPetInfoSuccess(AccountPet accountPublic) {

    }

    @Override
    public void uploadHead(String user) {
        GlideUtil.load(mActivity, user, mIvHead);
       account.setUser_headimg(user);
    }



    @Override
    public void upPetInfoSuccesss() {

    }

    @Override
    public void getPetCategorySuccess(List<PetCateFirst> petCateFirst) {

    }

    @Override
    public void getPetColorSuccess(List<PetColor> petColor) {

    }

    @Override
    public void deletePetSuccess() {

    }

    @Override
    public void upPersonInfoSuccess() {
        ToastUtil.getToastUtil().showShort(getString(R.string.add_address_success));
        mIsDel = true;
        finish();
    }
    @Override
    public void finish() {
        if (!mIsDel) {
            DialogUtil.createDialog(mActivity, getString(R.string.is_cancel_add_shou_huo_dizhi), getString(R.string.confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mIsDel = true;
                 finish();
                }
            }).show();
        } else {
            super.finish();
        }

    }

    private void setSex(int type) {
        if (type == 0) {
            tvSex.setText("保密");
        } else {
            tvSex.setCompoundDrawablesWithIntrinsicBounds(type == 1 ? drawableMale : drawableFamale,
                    null, null, null);
            tvSex.setText(1==type?"男":"女");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void compressComplete(File file) {
        mAccountPresenter.uploadHead(file, "avator");
    }

    @Override
    public void photoCallback(String path) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PhotoManager.REQUEST_CODE_CHECK_IMAGE:
                    //选择图片回调 并裁剪
                    ArrayList<ImageItem> path = data.getParcelableArrayListExtra("path");
                    mFile = new File(mFileUtil.getHeaderDir().getPath(), System.currentTimeMillis() + ".jpg");
                    PhotoManager.crop(this, mFile, new File(path.get(0).getImagePath()), PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_OPEN_CAMERA:
                    //相机回调
                    PhotoManager.crop(this, mFile, mFile, PhotoManager.REQUEST_CODE_CROP_CODE);
                    break;
                case PhotoManager.REQUEST_CODE_CROP_CODE:
                    //裁剪回调
                    //压缩
                    mPhotoPresenter.compressPhoto(mFile);
                    break;

            }
        }
    }
}
